package com.qxp.simplerpc.utils;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * @author qianxp
 *
 * classutils mainly contains some reflact method to res0lve the common simple requires
 *
 */
public class ClassUtils {

    // the logger utils
    private static final Logger logger = LoggerFactory.getLogger(ClassUtils.class);

    /**
     *. it should be common class and two different instance to equals the field if any equals
     *
     * @param cls the common class
     * @param target one of the instance
     * @param shade another instance
     * @return if any filed value is same
     */
    public static boolean ifAnyFieldsEqual(Class<?> cls,Object target, Object shade){
        boolean result = false;
        // 获取属性
        Field[] fields = cls.getDeclaredFields();
        try {
            for(Field field : fields){
                field.setAccessible(true);
                Object targetField =field.get(target);
                Object shadeField = field.get(shade);
                // any field is null,equ is no meaning
                if(targetField == null || shadeField == null){
                    continue;
                }
                // object value is equal
                if(targetField.equals(shadeField)){
                    result = true; break;
                }else
                // serialize the object to equal
                if(JSON.toJSONString(targetField).equals(JSON.toJSONString(shadeField))){
                    result = true; break;
                }
            }
        } catch (IllegalAccessException e) {
            logger.error("method can't be access...",e);
        }
        return result;
    }
}
